﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessLogic;
using BusinessObjects;
using DCMS_Framework;
using DCMSExceptions;

namespace Presentation {
  /// <summary>
  /// Zipcode list form
  /// </summary>
  public partial class ZipcodeListForm : Form {

    private CityZipcode cityZipcode;
    private ZipcodeBll bll = new ZipcodeBll( );
    private SortableBindingList<CityZipcode> zipcodeList;
    private List<Country> countryList = new List<Country>( );

    #region - Properties -

    /// <summary>
    /// Gets the zipcode.
    /// </summary>
    public CityZipcode Zipcode {
      get { return cityZipcode; }
    }

    #endregion

    #region - Constructors -

    /// <summary>
    /// Initializes a new instance of the <see cref="ZipcodeListForm"/> class.
    /// </summary>
    public ZipcodeListForm( ) {
      InitializeComponent( );
      zipcodeGridView.AutoGenerateColumns = false;
      zipcodeGridView.DataSource = zipcodeBindingSource;
    }

    #endregion

    #region - Events -

    private void ZipcodeListForm_Load( object sender, EventArgs e ) {

      Country emptyCountry = new Country( );
      emptyCountry.CountryId = 0;
      emptyCountry.CountryName = "Alles";

      countryList = bll.GetCountries( );
      countryList.Add( emptyCountry );

      countriesBindingSource.DataSource = countryList;

      GetZipcodes( );
      RebindZipcodes( );
    }

    private void zipcodeGridView_CellDoubleClick( object sender, DataGridViewCellEventArgs e ) {
      okButton.PerformClick( );
    }

    private void ZipcodeListForm_FormClosing( object sender, FormClosingEventArgs e ) {
      if ( zipcodeGridView.SelectedRows.Count > 0 ) {
        cityZipcode = ( CityZipcode ) zipcodeGridView.SelectedRows[ 0 ].DataBoundItem;
        cityZipcode.MarkClean( );
      }
    }

    private void countryComboBox_SelectedIndexChanged( object sender, EventArgs e ) {
      GetZipcodes( );
      RebindZipcodes( );
    }

    private void refreshButton_Click( object sender, EventArgs e ) {
      GetZipcodes( );
      RebindZipcodes( );
    }

    #endregion

    #region - Methods -

    private void RebindZipcodes( ) {
      zipcodeBindingSource.DataSource = null;
      zipcodeBindingSource.DataSource = zipcodeList;
    }

    private void GetZipcodes( ) {
      try {
        if ( ( int ) countryComboBox.SelectedValue == 0 ) {
          zipcodeList = bll.GetAllZipcodes( );
        } else {
          zipcodeList = bll.GetZipcodesByCountry( ( int ) countryComboBox.SelectedValue );
        }
      } catch ( BusinessException ex ) {
        MessageBox.Show( this.MdiParent, ex.Message, "Fout ophalen postcodes", MessageBoxButtons.OK, MessageBoxIcon.Error );
      }

    }

    #endregion

  }
}
